#!/bin/bash
# MySQL 8 部署脚本

set -e

echo "=========================================="
echo "部署 MySQL 8"
echo "=========================================="

# 检查 kubectl 是否可用
if ! command -v kubectl &> /dev/null; then
    echo "错误: kubectl 未安装或不在 PATH 中"
    exit 1
fi

# 设置 KUBECONFIG 环境变量（k3s 配置）
if [ -f /etc/rancher/k3s/k3s.yaml ]; then
    export KUBECONFIG=/etc/rancher/k3s/k3s.yaml
elif [ -f ~/.kube/config ]; then
    export KUBECONFIG=~/.kube/config
elif [ -f /root/.kube/config ]; then
    export KUBECONFIG=/root/.kube/config
fi

# 1. 创建 ConfigMap
echo "[1/5] 创建 ConfigMap..."
kubectl apply -f k8s/mysql/configmap.yaml

# 2. 创建 Secret
echo "[2/5] 创建 Secret..."
kubectl apply -f k8s/mysql/secret.yaml

# 3. 确保数据目录权限正确
echo "[3/6] 检查数据目录权限..."
if [ -d /data/mysql ]; then
    chown -R 999:999 /data/mysql 2>/dev/null || echo "警告: 无法设置目录权限（可能需要 root）"
    chmod -R 750 /data/mysql 2>/dev/null || echo "警告: 无法设置目录权限（可能需要 root）"
    echo "✓ 数据目录权限已检查"
else
    echo "警告: /data/mysql 不存在，请先运行 prepare-storage.sh"
fi

# 4. 创建 PVC
echo "[4/6] 创建 PersistentVolumeClaim..."
kubectl apply -f k8s/mysql/pvc.yaml

# 等待 PVC 绑定（WaitForFirstConsumer 模式下，PVC 在 Pod 调度后才会绑定）
echo "注意: PVC 将在 Pod 调度后自动绑定（WaitForFirstConsumer 模式）"

# 5. 部署 StatefulSet
echo "[5/6] 部署 StatefulSet..."
kubectl apply -f k8s/mysql/statefulset.yaml

# 6. 创建 Service
echo "[6/6] 创建 Service..."
kubectl apply -f k8s/mysql/service.yaml

# 等待 Pod 就绪
echo ""
echo "等待 MySQL Pod 启动..."
echo "提示: 首次部署需要拉取镜像，可能需要 2-5 分钟"
echo "可以按 Ctrl+C 退出等待，然后运行 'kubectl get pods -l app=mysql' 查看状态"
echo ""

# 使用循环等待，每 10 秒显示一次状态
WAIT_TIME=0
MAX_WAIT=300
while [ $WAIT_TIME -lt $MAX_WAIT ]; do
    POD_STATUS=$(kubectl get pods -l app=mysql -o jsonpath='{.items[0].status.phase}' 2>/dev/null || echo "")
    POD_READY=$(kubectl get pods -l app=mysql -o jsonpath='{.items[0].status.conditions[?(@.type=="Ready")].status}' 2>/dev/null || echo "False")
    
    if [ "$POD_READY" = "True" ]; then
        echo "✓ MySQL Pod 已就绪！"
        break
    fi
    
    if [ "$POD_STATUS" = "Running" ]; then
        echo "Pod 状态: Running, 等待就绪... (${WAIT_TIME}s/${MAX_WAIT}s)"
    elif [ "$POD_STATUS" = "Pending" ]; then
        # 检查是否在拉取镜像
        REASON=$(kubectl get pods -l app=mysql -o jsonpath='{.items[0].status.containerStatuses[0].state.waiting.reason}' 2>/dev/null || echo "")
        if [ "$REASON" = "ContainerCreating" ] || [ "$REASON" = "PodInitializing" ]; then
            echo "Pod 状态: 正在创建容器/拉取镜像... (${WAIT_TIME}s/${MAX_WAIT}s)"
        else
            echo "Pod 状态: Pending - $REASON (${WAIT_TIME}s/${MAX_WAIT}s)"
        fi
    else
        echo "Pod 状态: $POD_STATUS (${WAIT_TIME}s/${MAX_WAIT}s)"
    fi
    
    sleep 10
    WAIT_TIME=$((WAIT_TIME + 10))
done

if [ $WAIT_TIME -ge $MAX_WAIT ]; then
    echo "⚠ 警告: Pod 在 ${MAX_WAIT} 秒内未就绪"
    echo "请手动检查: kubectl get pods -l app=mysql"
    echo "查看详情: kubectl describe pod mysql-0"
fi

# 显示状态
echo ""
echo "=========================================="
echo "MySQL 部署状态"
echo "=========================================="
kubectl get pods -l app=mysql
kubectl get svc -l app=mysql

echo ""
echo "=========================================="
echo "MySQL 部署完成！"
echo "=========================================="
echo ""
echo "连接信息："
echo "  ClusterIP: mysql:3306"
echo "  NodePort: <节点IP>:30306"
echo ""
echo "测试连接："
echo "  kubectl run -it --rm mysql-client --image=mysql:8.0 --restart=Never -- mysql -h mysql -uroot -proot"

